package com.example.zhinongbao.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.zhinongbao.R;
import com.example.zhinongbao.bean.Contact;
import com.example.zhinongbao.bean.Message;
import com.example.zhinongbao.utils.Constant;
import com.example.zhinongbao.utils.FragmentUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 联系人适配器
 */
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
    private List<Contact> mDataList = new ArrayList<>();
    private View.OnClickListener listener;

    public ContactAdapter(List<Contact> dataList) {
        this.mDataList = dataList;
    }

    @NonNull
    @Override
    public ContactAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact, parent, false);
        ContactAdapter.ViewHolder holder = new ContactAdapter.ViewHolder(view);
        return holder;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Contact contact = mDataList.get(position);
        holder.text_name.setText(contact.getName());
        holder.text_message.setText(contact.getMessage());
        holder.text_time.setText(contact.getTime().toLocaleString());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 保存当前点击的这个联系人的名字和消息内容到全局变量中，跳转到聊天页面
                Constant.currentChatPerson = contact.getName();
                Constant.currentMsg.clear();
                Constant.currentMsg.add(new Message(0, contact.getMessage()));
                FragmentUtils.getInstance().switchFragment(R.id.nav_chat);
            }
        });

    }

    @Override
    public int getItemCount() {
        if (mDataList != null) {
            return mDataList.size();
        }
        return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView text_name;
        TextView text_message;
        TextView text_time;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            text_name = itemView.findViewById(R.id.text_name);
            text_message = itemView.findViewById(R.id.text_message);
            text_time = itemView.findViewById(R.id.text_time);
        }
    }
}
